package com.example.demo.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.example.demo.annotation.BaseInterceptorTest;
import com.example.demo.component.Settings;

@Component
public class BaseInterceptor implements HandlerInterceptor{
	
	private static final Logger logger = LogManager.getLogger(BaseInterceptor.class);
	
	@Autowired
	private Settings settings;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) {
		
		logger.info("BaseInterceptor preHandle object:" + object);
		logger.info("BaseInterceptor preHandle settings:" + settings);
		logger.info("BaseInterceptor preHandle session:" + request.getSession().getAttribute("username"));
		
		if(!(object instanceof HandlerMethod)){
			return true;
		}
		
		HandlerMethod handlerMethod=(HandlerMethod)object;
		Method method=handlerMethod.getMethod();
		// 使用注解
		if (method.isAnnotationPresent(BaseInterceptorTest.class)) {
			BaseInterceptorTest baseInterceptorTest = method.getAnnotation(BaseInterceptorTest.class);
			 logger.info("BaseInterceptor preHandle baseInterceptorTest:" + baseInterceptorTest.required());
		}
	
		return true;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable ModelAndView modelAndView) throws Exception {
		logger.info("BaseInterceptor postHandle settings:" + settings);
		logger.info("BaseInterceptor postHandle session:" + request.getSession().getAttribute("username"));
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable Exception ex) throws Exception {
		logger.info("BaseInterceptor afterCompletion settings:" + settings);
		logger.info("BaseInterceptor afterCompletion session:" + request.getSession().getAttribute("username"));
	}
}
